package com.ithinks.flow.common.utils.protocol.netty.udp.broadcast.acceptside;

import com.ithinks.flow.common.utils.protocol.udp.broadcast.LogConst;
import com.ithinks.flow.common.utils.protocol.udp.broadcast.acceptside.LogEventDecoder;
import com.ithinks.flow.common.utils.protocol.udp.broadcast.acceptside.LongEventHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.net.InetSocketAddress;

/**
 * @Description
 * @ClassName LogEventMonitor
 * @Author MR.LI
 * @date 2020.12.13 17:36
 */
public class LogEventMonitor {
    private final EventLoopGroup group;
    private final Bootstrap bootstrap;

    public LogEventMonitor(InetSocketAddress address){
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .option(ChannelOption.SO_REUSEADDR,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new LogEventDecoder());
                        pipeline.addLast(new LongEventHandler());
                    }
                }).localAddress(address);
    }

    public Channel bind(){
        //DatagramChannels是无连接的，
        return bootstrap.bind().syncUninterruptibly().channel();
    }

    public void stop(){
        group.shutdownGracefully();
    }

    public static void main(String[] args) {
        LogEventMonitor monitor  = new LogEventMonitor(
                new InetSocketAddress(LogConst.MONITOR_SIDE_PORT));
        Channel channel = monitor.bind();
        System.out.println("udp answer side running");
        try {
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            monitor.stop();
        }
    }
}
